package dp.mobile.eden;

import org.w3c.dom.Node;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import dp.mobile.level.CutScene.MiniDialog;
import dp.mobile.level.Dialog;
import dp.mobile.level.Level;
import dp.mobile.system.Utilities;
import dp.mobile.system.XMLReader;

public class DialogAct extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.conversation_dialog);
        
        String intentLevel	= getIntent().getExtras().getString("level"); 
        int intentWave		= getIntent().getExtras().getInt("wave");
        
        Node node = XMLReader.instance().parseXML(Utilities.LEVEL_FOLDER + "/" + intentLevel);
    	Level level = new Level(node);
    	mDialog = level.getDialog(intentWave);
    	mDialog.loadCharacterImg();
        
        mOkArrow = (ImageView)findViewById(R.id.ok);
        mOkArrow.setBackgroundResource(R.anim.ui_button);
		mOkAnimation = (AnimationDrawable) mOkArrow.getBackground();
		mOkArrow.setVisibility(View.INVISIBLE);
		
		mSpeaker1 = (ImageView)findViewById(R.id.speaker1);
		mSpeaker2 = (ImageView)findViewById(R.id.speaker2);
        
    	TypewriterTextView tv = (TypewriterTextView)findViewById(R.id.typewritertext);   
    	tv.setParentActivity(this);
    	
    	System.gc();
    }
    
	@Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            TypewriterTextView tv = (TypewriterTextView)findViewById(R.id.typewritertext);        
            
            if (tv.getRemainingTime() > 0) {
                tv.snapToEnd();
            } else {
                mCurrentPage++;
                if (mCurrentPage < mDialog.getDialogs().get(mDialog.getPosition()).size()) {
                    showPage(mDialog.getDialogs().get(mDialog.getPosition()).get(mCurrentPage));
                } else {
                    finish();
                }
            }
        }
        // Sleep so that the main thread doesn't get flooded with UI events.
        try {
            Thread.sleep(32);
        } catch (InterruptedException e) {
            // No big deal if this sleep is interrupted.
        }
        return true;
    }
    
	protected void showPage(MiniDialog page) {
        TypewriterTextView tv = (TypewriterTextView)findViewById(R.id.typewritertext);        
        tv.setTypewriterText(page.getText());
        
		mOkArrow.setVisibility(View.INVISIBLE);
		mOkAnimation.start();

		tv.setOkArrow(mOkArrow);
        
        TextView title = (TextView)findViewById(R.id.speakername);
        
        //Reset
        mSpeaker1.setVisibility(View.GONE);
        mSpeaker2.setVisibility(View.GONE);
        
        if (page.getSpeaker() != null) {
            title.setText(page.getSpeaker());
            title.setVisibility(View.VISIBLE);
            
            //Check speaker
            if (page.getSpeaker().equals("Adam")) mSpeaker1.setVisibility(View.VISIBLE);
            else if (page.getSpeaker().equals("Mike")) mSpeaker2.setVisibility(View.VISIBLE);
        } else {
        	title.setVisibility(View.GONE);
        }
    }
    
    public void processText() {
		TextView textView = (TextView)findViewById(R.id.typewritertext);
		//formatPages(mDialog, textView);

    	showPage(mDialog.getDialogs().get(mDialog.getPosition()).get(0));
        mCurrentPage = 0;
    }
    
    
    public static class TypewriterTextView extends TextView {
        private int mCurrentCharacter;
        private long mLastTime;
        private CharSequence mText;
        private View mOkArrow;
        private DialogAct mParentActivity;  // This really sucks.
        
        public TypewriterTextView(Context context) {
            super(context);
        }
        
        public TypewriterTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
        
        public TypewriterTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
        
        public void setParentActivity(DialogAct parent) {
        	mParentActivity = parent;
        }
        
        public void setTypewriterText(CharSequence text) {
            mText = text;
            mCurrentCharacter = 0;
            mLastTime = 0;
            postInvalidate();
        }
        
        public long getRemainingTime() {
            return (mText.length() - mCurrentCharacter) * TEXT_CHARACTER_DELAY_MS;
        }
        
        public void snapToEnd() {
            mCurrentCharacter = mText.length() - 1; 
        }
        
        public void setOkArrow(View arrow) {
        	mOkArrow = arrow;
        }
        
        
		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			// We need to wait until layout has occurred before we can setup the
			// text page.  Ugh.  Bidirectional dependency!  
			if (mParentActivity != null) {
				mParentActivity.processText();
			}
			super.onSizeChanged(w, h, oldw, oldh);
		}

		@Override
        public void onDraw(Canvas canvas) {
            final long time = SystemClock.uptimeMillis();
            final long delta = time - mLastTime;
            if (delta > TEXT_CHARACTER_DELAY_MS) {
                if (mText != null) {
                    if (mCurrentCharacter <= mText.length()) {
                        CharSequence subtext = mText.subSequence(0, mCurrentCharacter);
                        setText(subtext, TextView.BufferType.SPANNABLE);
                        mCurrentCharacter++;
                        postInvalidateDelayed(TEXT_CHARACTER_DELAY_MS);
                    } else {
                    	if (mOkArrow != null) {
                    		mOkArrow.setVisibility(View.VISIBLE);
                    	}
                    }
                }
            }
            super.onDraw(canvas);
        }
    }
    
    private final static float TEXT_CHARACTER_DELAY = 0.1f;
    private final static int TEXT_CHARACTER_DELAY_MS = (int)(TEXT_CHARACTER_DELAY * 1000);
    private Dialog mDialog;
    private int mCurrentPage;
    
    private ImageView mOkArrow;
    private ImageView mSpeaker1, mSpeaker2;
    private AnimationDrawable mOkAnimation;

}
